<script lang="ts" setup>
import { ref, onMounted, h, computed } from 'vue'
import { ElMessage } from 'element-plus'
import gdjdService from '@/api/gdjd'
import { useMainStore } from '@/store/main'
import dayjs from 'dayjs'
import { TableItem } from '@/api/common'
import TreeUtilDTO from '@/utils/tree'
import treeSelect from '@/components/tree-select-edl/treeSelect.vue'
import ExportUtil from '@/utils/table-export'
import xtpzService from '@/api/xtpz'

const mainStore = useMainStore()
// 入参
const currentLevel = ref(1)
const exportParam = ref({
  url: '',
  params: {},
})
// 能否生成报表
const generateReportable = computed(() => mainStore.userInfo.anqxList.includes('003002b001'))
// 生命周期
onMounted(async () => {
  queryDlrsjqx()
})
/*
 * 查询承办单位
 */
const loading = ref<boolean>(false)

const dwList = ref<any[]>([])
const bmList = ref<any[]>([])
const privateData = ref(false)

const queryDlrsjqx = () => {
  xtpzService.getDlrsjqx({}).then((res: any) => {
    if (!res.data.txbmList) {
      privateData.value = true
      currentLevel.value = 3
      form.value.cbbmbm = mainStore.userInfo.bmbm
      form.value.cbdwbm = mainStore.userInfo.dwbm
      form.value.xzlx = '2'
      dwbmList.value = [{ dwbm: mainStore.userInfo.dwbm, dwmc: mainStore.userInfo.dwmc }]
      checkRowClick({
        cbbmbm: mainStore.userInfo.bmbm,
        cbdwbm: mainStore.userInfo.dwbm,
      })
    } else {
      dwList.value = TreeUtilDTO.getTreeData(
        (res.data.sqdwxxList || []).map((el: any) => ({
          ...el,
          mc: el.dwmc,
          dm: el.dwbm,
          fdm: el.fdwbm,
        })),
        'dwbm',
        'fdwbm',
      )
      bmList.value = res.data.txbmList || []
      if (form.value.dwbmList.length === 0) {
        const flattenList = res.data.sqdwxxList?.map((el: any) => el.dwbm)
        form.value.dwbmList.push(...flattenList)
        cbdwbmChange()
      }
      form.value.xzlx = '1'
      queryTable()
    }
  })
}

// 办结日期
const createTime = ref([new Date(new Date().getFullYear(), 0, 1), new Date()])

/*
 * 查询列表数据
 */
// 案卷退改监督
// 更多条件查询
const form = ref<any>({
  dwbmList: [] as string[], // 单位编码
  cbdwbm: '',
  cbbmbm: '',
  bjksrq: '', // 办结开始日期
  bjjsrq: '', // 办结结束日期
  sjlx: '1',
  xzlx: '1',
})

// 表格数据
const tableData = ref<TableItem>({
  data: [],
  titles: [
    {
      label: '承办单位',
      prop: 'cbdwmc',
      width: 300,
      custom: true,
    },
    { label: '退改案件数(件)', prop: 'tgajs', width: 150 },
    { label: '退改数(次)', prop: 'tgcs', width: 130 },
    { label: '按期退改数(次)', prop: 'aqtgcs', width: 150 },
    { label: '占比(%)', prop: 'aqtgzb', width: 100 },
    { label: '超期退改数(次)', prop: 'cqtgcs', width: 150 },
    { label: '占比(%)', prop: 'cqtgzb', width: 100 },
    { label: '退改中(次)', prop: 'tgz', width: 130 },
    { label: '占比(%)', prop: 'tgzzb', width: 100 },
  ],
})

const queryTable = (refresh?: boolean) => {
  const params = {
    cbdwbmList: dwbmList.value.map((item) => {
      return {
        dwbm: item.dwbm,
        dwmc: item.dwmc,
      }
    }),
    bmbm: form.value.cbbmbm,
    cbdwbm: form.value.cbdwbm,
    tgksrq: createTime.value?.length ? dayjs(createTime.value[0]).format('YYYY-MM-DD') : '',
    tgjsrq: createTime.value?.length ? dayjs(createTime.value[1]).format('YYYY-MM-DD') : '',
    sjlx: form.value.sjlx as string,
    xzlx: form.value.xzlx,
  }
  exportParam.value = {
    url: `${window.IPCONFIG}/api/gdjd/queryAjtgjd`,
    params,
  }
  loading.value = true
  gdjdService
    .queryAjtgjd(params)
    .then((res) => {
      tableData.value.data = res.data
      if (refresh) ElMessage({ type: 'success', message: '刷新成功' })
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
    .finally(() => {
      loading.value = false
    })
}

/*
 * 导出excel
 */
const exportTable = (e: Event) => {
  e.preventDefault()
  // 表头
  const headerList = tableData.value.titles.map((el: any) => {
    return {
      prop: el.prop,
      label: el.label,
    }
  })
  const params = {
    total: tableData.value.data.length,
    http: {
      ...exportParam.value,
      dataStructure: ['data'],
    },
    excel: {
      wjmc: '案卷退改监督',
      headers: headerList,
    },
  }
  ExportUtil.allPage(params)
}

/*
 * 下钻查询部门列表数据
 */
const queryGdsxjdbm = (refresh?: boolean) => {
  const params = {
    cbdwbmList: dwbmList.value.map((item) => {
      return {
        dwbm: item.dwbm,
        dwmc: item.dwmc,
      }
    }),
    bmbm: form.value.cbbmbm,
    cbdwbm: form.value.cbdwbm,
    tgksrq: createTime.value?.length ? dayjs(createTime.value[0]).format('YYYY-MM-DD') : '',
    tgjsrq: createTime.value?.length ? dayjs(createTime.value[1]).format('YYYY-MM-DD') : '',
    sjlx: form.value.sjlx as string,
    xzlx: form.value.xzlx,
  }
  exportParam.value = {
    url: `${window.IPCONFIG}/api/gdjd/queryAjtgjd`,
    params,
  }
  loading.value = true
  gdjdService
    .queryAjtgjd(params)
    .then((res) => {
      tableData.value.data = res.data.map((item: any) => {
        return {
          ...item,
          cbdwbm: bmInfo.value.cbdwbm,
          cbdwmc: bmInfo.value.cbdwmc,
        }
      })
      if (refresh) ElMessage({ type: 'success', message: '刷新成功' })
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
    .finally(() => {
      loading.value = false
    })
}

/*
 * 下钻查询检察官列表数据
 */
const queryGdsxjdjcg = (refresh?: boolean) => {
  const params = {
    cbdwbmList: dwbmList.value.map((item) => {
      return {
        dwbm: item.dwbm,
        dwmc: item.dwmc,
      }
    }),
    bmbm: form.value.cbbmbm,
    cbdwbm: form.value.cbdwbm,
    tgksrq: createTime.value?.length ? dayjs(createTime.value[0]).format('YYYY-MM-DD') : '',
    tgjsrq: createTime.value?.length ? dayjs(createTime.value[1]).format('YYYY-MM-DD') : '',
    sjlx: form.value.sjlx as string,
    xzlx: form.value.xzlx,
  }
  exportParam.value = {
    url: `${window.IPCONFIG}/api/gdjd/queryAjtgjd`,
    params,
  }
  loading.value = true
  gdjdService
    .queryAjtgjd(params)
    .then((res) => {
      tableData.value.data = res.data
      if (refresh) ElMessage({ type: 'success', message: '刷新成功' })
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
    .finally(() => {
      loading.value = false
    })
}

/*
 * 点击单位/部门下钻查询列表
 */
const bmInfo = ref()
const ryInfo = ref()
const checkRowClick = (row?: any) => {
  switch (currentLevel.value) {
    case 1:
      form.value.sjlx = '1'
      queryDlrsjqx()
      tableData.value.titles[0] = {
        label: '承办单位',
        prop: 'cbdwmc',
        width: 300,
        custom: true,
      }
      break
    case 2:
      form.value.cbdwbm = row?.cbdwbm
      form.value.sjlx = '2'
      bmInfo.value = row
      queryGdsxjdbm()
      tableData.value.titles[0] = {
        label: '承办部门',
        prop: 'cbbmmc',
        width: 300,
        custom: true,
      }
      break
    case 3:
      form.value.cbbmbm = row?.cbbmbm
      form.value.cbdwbm = row?.cbdwbm
      form.value.sjlx = '3'
      ryInfo.value = row
      queryGdsxjdjcg()
      tableData.value.titles[0] = {
        label: '检察官',
        prop: 'cbjcg',
        width: 200,
      }
      break
  }
}

/*
 * 返回上一层
 */
const preStep = (e: Event) => {
  e.preventDefault()
  currentLevel.value--
  if (currentLevel.value === 1) {
    checkRowClick()
  } else if (currentLevel.value === 2) {
    checkRowClick(bmInfo.value)
  }
}

// 刷新
const curren2Refresh = (e: Event) => {
  e.preventDefault()
  if (currentLevel.value === 2) {
    queryGdsxjdbm(true)
  }

  if (currentLevel.value === 3) {
    queryGdsxjdjcg(true)
  }
}

/*
 * 生成报表
 */
const generateReport = () => {
  const params = {
    cbdwbmList: dwbmList.value.map((item) => {
      return {
        dwbm: item.dwbm,
        dwmc: item.dwmc,
      }
    }),
    cbbmbmList: bmList.value.map((el) => {
      return {
        bmbm: el.bmbm,
        bmmc: el.bmmc,
      }
    }),

    tgksrq: createTime.value?.length ? dayjs(createTime.value[0]).format('YYYY-MM-DD') : '',
    tgjsrq: createTime.value?.length ? dayjs(createTime.value[1]).format('YYYY-MM-DD') : '',
  }
  gdjdService
    .createAjtgbb(params)
    .then(() => {
      ElMessage({ type: 'success', message: '生成报表成功' })
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}

const dwbmList = ref<any[]>([])
const cbdwbmChange = () => {
  const treeList = TreeUtilDTO.flatten(dwList.value)
  dwbmList.value = []
  treeList.forEach((item: any) => {
    form.value.dwbmList?.forEach((el: any) => {
      if (item.dwbm === el) {
        dwbmList.value.push(item)
      }
    })
  })
}

// 排序
const sortChange = (obj: any) => {
  console.log(obj, 'obj.prop')
}

// 自定义合计方法
const getSummaries = (param: { columns: any[]; data: any[] }) => {
  const { columns, data } = param
  const sums: any[] = []
  const totalData = data.pop()
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = h('div', null, ['合计'])
      return
    } else {
      if (typeof totalData[column.property] === 'number') {
        sums.push(totalData[column.property])
      } else {
        sums.push('')
      }
    }
  })
  return sums
}
</script>
<template>
  <div class="container">
    <!--表单-->
    <div class="form-box">
      <el-form :model="form" ref="filterFormRef" inline label-width="100px">
        <el-form-item
          v-if="currentLevel === 1 && !privateData"
          prop="dwbmList"
          :rules="[
            {
              required: true,
              message: '必选',
            },
          ]"
          label="承办单位:"
        >
          <tree-select
            ref="treeSelectRef"
            style="width: 300px"
            v-model="form.dwbmList"
            @update:modelValue="cbdwbmChange"
            multiple
            showAllSelection
            node-key="dwbm"
            :treeProps="{
              children: 'children',
              label: 'dwmc',
              value: 'dwbm',
            }"
            :options="dwList"
            :clearable="false"
            :check-strictly="true"
            :isLeafNode="false"
          >
          </tree-select>
        </el-form-item>
        <el-form-item v-if="currentLevel === 1 || privateData" label="退改日期:">
          <el-date-picker
            style="width: 240px"
            v-model="createTime"
            type="daterange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :clearable="false"
          />
        </el-form-item>

        <el-form-item v-if="currentLevel === 2">
          <span class="zzjg">{{ bmInfo?.cbdwmc }}</span>
        </el-form-item>
        <el-form-item v-if="currentLevel === 3">
          <span class="zzjg">{{ ryInfo?.cbbmmc }}</span>
        </el-form-item>

        <el-form-item class="dwmcInfo">
          <div class="dwmcInfoButton">
            <button
              class="btn_operation"
              v-if="(currentLevel == 2 || currentLevel == 3) && !privateData"
              @click="exportTable"
            >
              <div class="btn-export"></div>
              导出EXCEL
            </button>
            <button
              class="btn_operation"
              @click="curren2Refresh"
              v-if="(currentLevel == 2 || currentLevel == 3) && !privateData"
            >
              <div class="btn-refresh"></div>
              刷新
            </button>
            <button
              class="btn_operation"
              @click="preStep"
              v-if="(currentLevel == 2 || currentLevel == 3) && !privateData"
            >
              <div class="btn-back"></div>
              返回
            </button>
          </div>
        </el-form-item>

        <el-form-item class="search" v-if="currentLevel === 1">
          <el-button type="primary" @click="() => queryTable()">查询</el-button>
        </el-form-item>
        <el-form-item class="search" v-if="privateData">
          <el-button type="primary" @click="queryGdsxjdjcg()">查询</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="button-group" v-if="currentLevel == 3 && privateData">
      <button class="btn_operation" @click="exportTable">
        <div class="btn-export"></div>
        导出EXCEL
      </button>
      <button class="btn_operation" @click="curren2Refresh">
        <div class="btn-refresh"></div>
        刷新
      </button>
    </div>

    <div class="button-group" v-if="currentLevel == 1">
      <button v-if="generateReportable" class="btn_operation" @click="generateReport">
        <div class="btn-export"></div>
        生成报表
      </button>
      <button class="btn_operation" @click="exportTable">
        <div class="btn-export"></div>
        导出EXCEL
      </button>
      <button class="btn_operation" @click="() => queryTable(true)">
        <div class="btn-refresh"></div>
        刷新
      </button>
    </div>
    <!-- 表格 -->
    <div class="table-box" v-loading="loading">
      <el-table
        border
        :data="tableData.data"
        stripe
        row-key="id"
        height="100%"
        @sort-change="sortChange"
        show-summary
        :summary-method="getSummaries"
      >
        <el-table-column label="序号" type="index" width="60"></el-table-column>
        <el-table-column
          v-for="column in tableData.titles"
          :key="column.prop"
          :prop="column.prop"
          :label="column.label"
          :min-width="column.width"
          sortable
          resizable
        >
          <template #default="{ row }">
            <div v-if="column.custom">
              <el-link
                type="primary"
                class="custom-link"
                :underline="false"
                @click="
                  () => {
                    currentLevel++
                    checkRowClick(row)
                  }
                "
                >{{ row[column.prop] }}</el-link
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>
<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;

  .form-box {
    margin-bottom: 10px;
    border-bottom: 1px solid #dae4f1;
    .zzjg {
      font-size: 20px;
      padding-right: 8px;
    }
    .el-form {
      display: flex;
      .el-form-item.dwmcInfo {
        flex: 1;
        width: 100%;
        display: flex;
        .dwmcInfoTitle {
          flex: 5;
        }
        .dwmcInfoButton {
          display: flex;
          flex: 2;
          justify-content: flex-end;
        }
      }
      .el-form-item.search {
        margin-right: 0px;
      }
    }
  }

  .el-table--border::after {
    width: 0;
  }
  :deep(.el-table__cell) {
    border-right: 0 !important;
  }
  :deep(.el-table__border-left-patch) {
    display: none;
  }

  .button-group {
    display: flex;
    justify-content: flex-end;
    // margin-right: 32px;
    margin-bottom: 10px;
  }

  .table-box {
    flex: 1;
    height: calc(100% - 100px);
  }
}
</style>
